package com.starbaba.messageManager.view;

import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.core.web.struts2.JsonResult;
import com.starbaba.messageManager.model.MessageVo;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.HttpConnectionUtils;
import com.starbaba.util.SendEmail;
import com.starbaba.utils.TaskExecutor;

public class MessageAction extends BaseAction implements ModelDriven<MessageVo> {

	private static final long serialVersionUID = 8845523934410342143L;
	
	private MessageVo messageVo;

	@Override
	public MessageVo getModel() {
		if (messageVo == null) {
			messageVo = new MessageVo();
		}
		return messageVo;
	}

	public void sendMessage() {
		Map<String, Object> parmas = new HashMap<String, Object>();
		try {
			final String mobileNum = messageVo.getMobileNum().trim().replaceAll("(\r\n|\r|\n|\n\r)", "");
			final String content = messageVo.getContent();
			final String memo = messageVo.getMemo();
			final String email = messageVo.getEmail();
			String pid = messageVo.getPid();
			String[] mobiles = mobileNum.split(",");
			List<String> successList = new ArrayList<String>();
			List<String> failedList = new ArrayList<String>();
			StringBuffer failedPhone = new StringBuffer();
			JsonResult json = new JsonResult();
			// 筛选不符合规格的号码
			for (String mobile : mobiles) {
				boolean isM = isMobileNO(mobile);
				if (!isM) {
					failedList.add(mobile);
					failedPhone.append(" ").append(mobile);
				} else {
					successList.add(mobile);
				}

			}
			// 如果有不符合规格号码，直接返回页面整改
			if (failedList != null && failedList.size() > 0) {
				json.setStatus("0");
				json.setMessage(failedPhone.toString());
				sendJsonMessage(json);
				return;
			}

			// 符合规格的号码，就发送短信
			if (successList != null && successList.size() > 0) {
				for (String mobile : successList) {
					send(mobile, content, memo, 1, Integer.parseInt(pid), null, 0);
				}
			}
			System.out.println("成功的短信条数：" + successList.size());
			System.out.println("失败的短信条数：" + failedList.size());
			json.setStatus("1");
			json.setMessage("发送成功，一共发送" + successList.size() + "条");
			sendJsonMessage(json);
			
			try {
				final String emailTitle = "短信推送服务_" + memo;
				final String emailContent = "内容:" + content + ", 共发送了:" + successList.size() + "条";
				TaskExecutor.getInstance().execute(new Runnable() {
					@Override
					public void run() {
						SendEmail.sendEmail(email, email, emailTitle, emailContent);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// return ActionSupport.SUCCESS;
	}
	
	private static void send(final String mobileNum, final String content, final String memo,
			final int limit, final int product, final String ip, final int code) {
		TaskExecutor.getInstance().execute(new Runnable() {
			@Override
			public void run() {
				try {
					JsonObject obj = new JsonObject();
					obj.add("phead", new JsonObject());
					obj.addProperty("mobileNum", mobileNum);
					obj.addProperty("content", content);
					obj.addProperty("memo", memo);
					obj.addProperty("limit", limit);
					obj.addProperty("product", product);
					obj.addProperty("ip", ip);
					obj.addProperty("code", code);
					ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
					list.add(new BasicNameValuePair("data", obj.toString()));
					list.add(new BasicNameValuePair("shandle", "0"));
					String response = HttpConnectionUtils.connection(
							Constant.COMMON_HOST
									+ "/loan_utils/common?funid=1&rd="
									+ System.currentTimeMillis(),
							HttpConnectionUtils.POST, list);
					
					LogService.info("send phone:" + mobileNum + ", content:"
							+ content + ", product:" + product + ", response:"
							+ response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^(1)\\d{10}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
}
